﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace Serviio.API
{
    public class ServiioDevice
    {
        public delegate void HostUpdatedHandler(ServiioDevice device);
        public event HostUpdatedHandler OnHostUpdated;
        
        private ServiioConnection conn = null;
        
        public string Uuid { get; private set; }
        public string IpAddress { get; private set; }
        public string Name { get; private set; }
        public string ProfileId { get; set; }
        public string Status { get; private set; }
        public string HostName { get; private set; }

        public ServiioDevice(ServiioConnection connection, string ipAddress, string name, string profileId)
        {
            conn = connection;
            Uuid = Guid.NewGuid().ToString();
            IpAddress = ipAddress;
            HostName = ipAddress;
            Name = name;
            ProfileId = profileId;
            Status = null;

            ResolveHostName();
        }
        
        internal ServiioDevice(ServiioConnection connection, string uuid, string ipAddress, string name, string profileId, string status)
        {
            conn = connection;
            Uuid = uuid;
            IpAddress = ipAddress;
            HostName = ipAddress;
            Name = name;
            ProfileId = profileId;
            Status = status;

            ResolveHostName();
        }

        public string ProfileName
        {
            get
            {
                return conn.Reference.Profiles[ProfileId];
            }
        }

        private void ResolveHostName()
        {
            try
            {
                Dns.BeginGetHostEntry(IpAddress, HostNameCallback, null);
            }
            catch { }
        }
        private void HostNameCallback(IAsyncResult result)
        {
            try
            {
                IPHostEntry hostEntry = Dns.EndGetHostEntry(result);
                if (hostEntry != null)
                {
                    HostName = hostEntry.HostName;
                    if (OnHostUpdated != null)
                        OnHostUpdated(this);
                }
            }
            catch { }
        }
    }
}
